package com.bdcom.autotest.telnet.invoke.impl;

import com.bdcom.autotest.telnet.TelnetClientForCOM;
import com.bdcom.autotest.telnet.TelnetCommunication;
import com.bdcom.autotest.telnet.constant.TelnetConstant;
import com.bdcom.autotest.telnet.invoke.DeveiceOper;
import com.bdcom.autotest.telnet.model.Result;
import com.bdcom.autotest.telnet.model.TelnetCMDObj;
import com.bdcom.autotest.telnet.model.UpgradeDefaultConfigObj;
import com.bdcom.autotest.telnet.util.TelnetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 只适用于默认配置文件升级
 */
public class DevUpgradeDefaultConfig implements DeveiceOper, TelnetConstant {
    private static final Logger logger = LoggerFactory.getLogger(DevUpgradeDefaultConfig.class);
    @Override
    public Result executeCMD(TelnetCMDObj obj) {
        String cmd="";
        String beforeCMD="";
        String afterCMD="";
        if(obj instanceof UpgradeDefaultConfigObj){
            cmd=((UpgradeDefaultConfigObj) obj).buidCMD();
            beforeCMD=((UpgradeDefaultConfigObj) obj).getBeforeCMD();
            afterCMD=((UpgradeDefaultConfigObj) obj).getAfterCMD();
        }
        Result result=new Result();
        TelnetClientForCOM clientForCOM=null;
        try {
            TelnetCommunication communication=new TelnetCommunication();
            clientForCOM=new TelnetClientForCOM(obj.getIp(),obj.getPort());
            Result loginResult=communication.login(obj.getUser(),obj.getPassword(),clientForCOM,obj.isMonitor());
            if(loginResult.getStatus()){
                Result enableResult = communication.enableOper(clientForCOM, obj.getEnablePassword(),obj.isMonitor());
                if(enableResult.getStatus()){
                    //1.升级前先执行beforeCMD（sh filesys-backdoor）
                      String retStr=clientForCOM.sendCommand(beforeCMD,1000L);
                      if(retStr.contains("filesys backdoor is ON")){
                          //开启，准备下一步升级
                      }else if(retStr.contains("filesys backdoor is OFF")){
                         //关闭，需要开启
                          retStr=clientForCOM.sendCommand(beforeCMD,1000L);
                          if(retStr.contains("filesys backdoor is ON")){

                          }else{
                              //开启失败
                              result.setStatus(false);
                              result.setFailedReason("Open filesys backdoor failed["+retStr+"]");
                              return result;
                          }
                      }else{
                          result.setStatus(false);
                          result.setFailedReason("filesys backdoor status["+retStr+"]");
                          return result;
                      }

                      //2.升级
                      retStr="";
                      if (obj.isMonitor()){
                        retStr=communication.sendCommandWithRetryForMonitorUpgrade(clientForCOM,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlagsForMonitor);
                      }else{
                        retStr=communication.sendCommandWithRetry(clientForCOM,EXEC_UPGRADE_MASTER_TIME,EXEC_UPGRADE_MASTER_RETRY_TIME,cmd,upgradeEndFlags);
                      }

                      result=TelnetUtil.executeStatus(retStr,cmd);
                      if(result.getStatus()){
                          //3.升级后，dir确认default-config已存在 再执行afterCMD（sh filesys-backdoor）
                          retStr=clientForCOM.sendCommand("dir",3000L);
                          if(retStr.contains("default-config")){
                              retStr=clientForCOM.sendCommand(afterCMD,1000L);
                              if(retStr.contains("filesys backdoor is OFF")){
                                  //关闭成功
                                  result.setStatus(true);
                                  return result;
                              }else{
                                  //关闭失败
                                  result.setStatus(false);
                                  result.setFailedReason("Close filesys backdoor failed!");
                                  return result;
                              }

                          }else{
                              result.setStatus(false);
                              result.setFailedReason("dir not find default-config");
                              return result;
                          }


                      }else{
                          return result;
                      }



                }else{
                    return enableResult;
                }
            }else{
                return loginResult;
            }
            

        }catch (Exception e){
            result.setFailedReason(e.toString());
            return result;
        }finally {
            if(null!=clientForCOM){
                try {
                    if(!obj.isMonitor()){
                        //非monitor模式下恢复telnet连接的COM口的初始状态
                        clientForCOM.sendCommand("exit",200L);
                        clientForCOM.sendCommand("exit",200L);
                    }
                    clientForCOM.disConnect();
                } catch (Exception e) {
                    logger.error(e.toString());
                }
            }
        }


    }
    public Result upgrade(UpgradeDefaultConfigObj obj){
        obj.setMonitor(true);//只能monitor升级
        Result result = executeCMD(obj);
        return result;


    }
}
